import { message } from '@/components/XtxUI';
import { http } from '@/utils/request';
import { defineStore } from 'pinia';
import { computed, ref } from 'vue';
import type { CartItem, CartList } from '@/types';
import { useMemberStore } from './member';

/*
  Pinia 组合式 Store：
    1. 所有 ref() 转换成 state
    2. 所有 computed() 转换成 getters
    3. 所有 函数 转换成 actions
*/

export const useCartStore = defineStore(
  'cart',
  () => {
    // 获取会员 Store
    const member = useMemberStore();
    // 加入购物车 object 修改成 CartItem，类型更精确
    const addCart = async (data: CartItem) => {
      if (member.isLogin) {
        // 解构出后端接口所需的两个参数
        const { count, skuId } = data;
        // 已登录情况：调用接口
        const res = await http('POST', '/member/cart', { count, skuId });
      } else {
        // 未登录：本地操作，判断当前商品是否已存在
        const index = list.value.findIndex((v) => v.skuId === data.skuId);
        //   已存在：数量叠加
        if (index > -1) {
          list.value[index].count += data.count;
        } else {
          // 不存在：数组前添加
          list.value.unshift(data);
        }
      }
      // 成功提示
      message({ type: 'success', text: '加入购物车成功' });
      // 加入成功后，主动获取最新购物车列表
      getCartList();
    };

    // 获取购物车列表
    const list = ref<CartList>([]);
    const getCartList = async () => {
      if (member.isLogin) {
        const res = await http<CartList>('GET', '/member/cart');
        list.value = res.data.result;
      } else {
        list.value.forEach(async (item) => {
          const res = await http<CartItem>('GET', `/goods/stock/${item.skuId}`);
          // console.log('GET', `/goods/stock/${item.skuId}`, res);
          // 更新商品现价，库存，有效状态
          item.nowPrice = res.data.result.nowPrice;
          item.stock = res.data.result.stock;
          item.isEffective = res.data.result.isEffective;
        });
      }
    };

    // 计算出有效商品列表
    const effectiveList = computed(() => {
      // 库存动态变化的，必须 stock 库存大于 0
      // 商品可能会下架，必须 isEffective 有效为 true
      return list.value.filter((v) => v.stock > 0 && v.isEffective);
    });

    // 计算商品总件数
    const effectiveListCount = computed(() => {
      let sum = 0;
      effectiveList.value.forEach((item) => {
        sum += item.count;
      });
      return sum;
    });

    // 计算商品总钱数
    const effectiveListPrice = computed(() => {
      let sum = 0;
      effectiveList.value.forEach((item) => {
        sum += item.count * Number(item.nowPrice);
      });
      // 🐛 小数运算精度BUG修复，保留两位小数即可
      return sum.toFixed(2);
    });

    // 删除商品
    const deleteCart = async (ids: string[]) => {
      if (member.isLogin) {
        const res = await http('DELETE', '/member/cart', { ids: ids });
      } else {
        list.value = list.value.filter((v) => v.skuId !== ids[0]);
      }
      getCartList();
    };

    // 修改购物车商品(修改选中状态和修改商品数量)
    const updateCart = async (skuId: string, data: object) => {
      if (member.isLogin) {
        const res = await http('PUT', `/member/cart/${skuId}`, data);
      } else {
        // 根据 skuId 查找待修改的商品项
        const index = list.value.findIndex((v) => v.skuId === skuId);

        // data 有两种情况：修改选中状态 selected , 修改数量 count
        // 解构出需要修改的字段，需升级 data 类型，否则无法从 object 中解构出字段
        const { selected, count } = data as {
          selected?: boolean;
          count?: number;
        };

        // 如果是 selected 就更新 selected
        if (selected !== undefined) {
          list.value[index].selected = selected;
        }

        // 如果是 count 就更新 count
        if (count !== undefined) {
          list.value[index].count = count;
        }
      }
      // 主动获取最新列表
      getCartList();
    };

    // 由前端计算全选状态
    const isAllSelected = computed(() => {
      return (
        effectiveList.value.length > 0 &&
        effectiveList.value.every((v) => v.selected)
      );
    });

    // 购物车全选/取消全选
    const updateCartAllSelected = async (selected: boolean) => {
      if (member.isLogin) {
        const res = await http('PUT', '/member/cart/selected', {
          selected: selected,
        });
      } else {
        // 🔔以下代码添加到：未登录分支内
        list.value.forEach((item) => {
          item.selected = selected;
        });
      }
      // 主动获取最新列表
      getCartList();
    };

    // 选中的商品列表
    const selectedList = computed(() => {
      return effectiveList.value.filter((v) => v.selected);
    });

    // 选中的商品列表-总件数
    const selectedListCount = computed(() => {
      // 计算方式1：forEach 写法
      // let sum = 0;
      // selectedList.value.forEach((item) => {
      //   sum += item.count;
      // });
      // return sum;

      // 计算方式2：reduce 写法
      return selectedList.value.reduce((sum, item) => sum + item.count, 0);
    });

    // 选中的商品列表-总钱数
    const selectedListPrice = computed(() => {
      let sum = 0;
      selectedList.value.forEach((item) => {
        sum += item.count * Number(item.nowPrice);
      });
      return sum.toFixed(2);
    });

    // 清空购物车
    const clearCart = () => {
      // 退出登录需清空购物车
      list.value = [];
    };

    // 合并购物车
    const mergeCart = async () => {
      const data = list.value.map((item) => {
        return {
          skuId: item.skuId,
          selected: item.selected,
          count: item.count,
        };
      });
      const res = await http('POST', '/member/cart/merge', data);
      getCartList();
    };

    // 记得 return
    return {
      addCart,
      getCartList,
      list,
      effectiveList,
      effectiveListCount,
      effectiveListPrice,
      deleteCart,
      updateCart,
      isAllSelected,
      updateCartAllSelected,
      selectedList,
      selectedListCount,
      selectedListPrice,
      clearCart,
      mergeCart,
    };
  },
  {
    // 开启 state/ref 持久化存储
    persist: {
      paths: ['list'],
    },
  }
);
